package com.users.rn.common.network.utils

import android.os.Environment
import android.text.TextUtils
import java.io.*
import java.nio.charset.Charset

/**

 * 作者：wolf on 3/4/21 17:47

 * 邮箱：bluce

 */

object FileUtil {
    /**
     * 删除文件夹
     *
     * @param folderPath 文件夹的路径
     */
    fun delFolder(folderPath: String) {
        delAllFile(folderPath)
        var filePath = folderPath
        filePath = filePath
        val myFilePath = File(filePath)
        myFilePath.delete()
    }

    /**
     * 删除单个文件
     * @param filePath 文件路径
     * @return 删除成功返回true 否则返回false
     */
    fun delFile(filePath: String?): Boolean {
        val file = File(filePath)
        return if (file.isFile && file.exists()) {
            file.delete()
        } else false
    }


    /**
     * 删除文件
     *
     * @param path 文件的路径
     */
    fun delAllFile(path: String) {
        val file = File(path)
        if (!file.exists()) {
            return
        }
        if (!file.isDirectory) {
            return
        }
        val tempList = file.list() ?: return
        var temp: File? = null
        for (i in tempList.indices) {
            if (path.endsWith(File.separator)) {
                temp = File(path + tempList[i])
            } else {
                temp = File(path + File.separator + tempList[i])
            }
            if (temp.isFile()) {
                temp.delete()
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i])
                delFolder(path + "/" + tempList[i])
            }
        }
    }


    /**********************************************************************************************************/
    /*********************************************************************************************************/
    /** */
    /** */
    /**
     * 删除一个文件
     *
     * @param file
     * @return
     */
    fun delFile(file: File): Boolean {
        return if (file.isDirectory) false else file.delete()
    }

    /**
     * 删除一个目录（可以是非空目录）
     *
     * @param dir
     */
    fun delDir(dir: File?): Boolean {
        if (dir == null || !dir.exists() || dir.isFile) {
            return false
        }
        for (file: File in dir.listFiles()) {
            if (file.isFile) {
                file.delete()
            } else if (file.isDirectory) {
                delDir(file) // 递归
            }
        }
        dir.delete()
        return true
    }

    /**
     * 拷贝一个文件,srcFile源文件，destFile目标文件
     *
     * @param srcFile
     * @throws IOException
     */
    @Throws(IOException::class)
    fun copyFileTo(srcFile: File, destFile: File): Boolean {
        if (srcFile.isDirectory || destFile.isDirectory) return false // 判断是否是文件
        val fis = FileInputStream(srcFile)
        val fos = FileOutputStream(destFile)
        var readLen = 0
        val buf = ByteArray(1024)
        while (fis.read(buf).also { readLen = it } != -1) {
            fos.write(buf, 0, readLen)
        }
        fos.flush()
        fos.close()
        fis.close()
        return true
    }

    /**
     * 拷贝目录下的所有文件到指定目录
     *
     * @param srcDir
     * @param destDir
     * @return
     * @throws IOException
     */
    @Throws(IOException::class)
    fun copyFilesTo(srcDir: File, destDir: File): Boolean {
        if (!srcDir.isDirectory || !destDir.isDirectory) return false // 判断是否是目录
        if (!destDir.exists()) return false // 判断目标目录是否存在
        val srcFiles = srcDir.listFiles()
        for (i in srcFiles.indices) {
            if (srcFiles[i].isFile) {
                // 获得目标文件
                val destFile = File(
                    destDir.path + "//"
                            + srcFiles[i].name
                )
                copyFileTo(srcFiles[i], destFile)
            } else if (srcFiles[i].isDirectory) {
                val theDestDir = File(
                    (destDir.path + "//"
                            + srcFiles[i].name)
                )
                copyFilesTo(srcFiles[i], theDestDir)
            }
        }
        return true
    }

    fun mkdirs(fileDir: String?) {
        val dir = File(fileDir)
        if (!dir.exists()) {
            dir.mkdirs()
        }
    }

    fun createFile(filePath: String?): File? {
        if (TextUtils.isEmpty(filePath)) {
            return null
        }
        val state = Environment.getExternalStorageState()
        val file = File(filePath)
        val dir = file.parentFile
        var successed = true
        if (dir.exists()) {
            if (!dir.isDirectory) {
                dir.delete()
                successed = dir.mkdirs()
            }
        } else {
            successed = dir.mkdirs()
        }
        if (!successed) {
            return null
        }
        if (!file.exists()) {
            try {
                file.createNewFile()
            } catch (e: IOException) {
                return null
            }
        }
        return file
    }

    /**
     * 移动一个文件
     *
     * @param srcFile
     * @param destFile
     * @return
     * @throws IOException
     */
    @Throws(IOException::class)
    fun moveFileTo(srcFile: File, destFile: File): Boolean {
        val iscopy = copyFileTo(srcFile, destFile)
        if (!iscopy) return false
        delFile(srcFile)
        return true
    }

    /**
     * 移动目录下的所有文件到指定目录
     *
     * @param srcDir
     * @param destDir
     * @return
     * @throws IOException
     */
    @Throws(IOException::class)
    fun moveFilesTo(srcDir: File, destDir: File): Boolean {
        if (!srcDir.isDirectory || !destDir.isDirectory) {
            return false
        }
        val srcDirFiles = srcDir.listFiles()
        for (i in srcDirFiles.indices) {
            if (srcDirFiles[i].isFile) {
                val oneDestFile = File(destDir.path + File.separator + srcDirFiles[i].name)
                moveFileTo(srcDirFiles[i], oneDestFile)
                delFile(srcDirFiles[i])
            } else if (srcDirFiles[i].isDirectory) {
                val oneDestFile = File(destDir.path + File.separator + srcDirFiles[i].name)
                if (!oneDestFile.exists()) {
                    oneDestFile.mkdirs()
                }
                moveFilesTo(srcDirFiles[i], oneDestFile)
                delDir(srcDirFiles[i])
            }
        }
        return true
    }

    class Output(outputStream: OutputStream, bytes: ByteArray?) {
        init {
            outputStream.write(bytes)
            outputStream.flush()
            outputStream.close()
        }
    }

    private class Input(var inputStream: InputStream) {
        fun read(): String? {
            var content: String? = null
            val length: Int
            try {
                length = inputStream.available()
                val buffer = ByteArray(length)
                inputStream.read(buffer)
                content = String(buffer, Charset.forName("UTF-8"))
                inputStream.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return content
        }
    }

    /**
     * 获得百分比
     * @return
     */
    fun getPrecent(current: Long, sum: Long): Int {
        return if (sum <= 0) {
            0
        } else (current * 100 / sum).toInt()
    }

    /**
     * 获得文件名
     * @param url
     * 文件下载链接
     * @param filename
     * 用户发送过来的文件名
     * @return
     * 处理后的文件名，如用户发送的名字为空则返回默认值
     */
    fun getFileName(url: String, filename: String?): String? {
        if (TextUtils.isEmpty(url)) {
            return ""
        }
        return if (TextUtils.isEmpty(filename)) {
            url.substring(
                url.lastIndexOf("/") + 1,
                if (url.lastIndexOf("?") > 0) url.lastIndexOf("?") else url.length
            )
        } else {
            filename
        }
    }

    fun createFile(fileName: String, path: String): File? {
        if (TextUtils.isEmpty(fileName) || TextUtils.isEmpty(path)) {
            //文件名或者路径为空
            return null
        }
        val filePath = File(path)
        if (!filePath.exists()) {
            return null
        }
        val filepath = if (path.endsWith("/")) path + fileName else "$path/$fileName"
        val file = File(filepath)
        if (!file.exists()) {
            try {
                file.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
                return null
            }
            return file
        }
        return file
    }

    fun checkFile(fileName: String, path: String): Boolean {
        if (TextUtils.isEmpty(fileName) || TextUtils.isEmpty(path)) {
            //文件名或者路径为空
            return false
        }
        val filePath = File(path)
        if (!filePath.exists()) {
            return false
        }
        val file = File("$path/$fileName")
        return file.exists()
    }

    fun readContent(filePath: String?): String? {
        try {
            val buffer = ByteArray(File(filePath).length().toInt())
            val fis = FileInputStream(File(filePath))
            fis.read(buffer)
            fis.close()
            return String(buffer)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun closeQuietly(vararg closeables: Closeable?) {
        if (closeables != null) {
            for (closeable: Closeable? in closeables) {
                try {
                    closeable?.close()
                } catch (e: Exception) {
                }
            }
        }
    }
}